package com.tx.activemq._01_c_p._01_queue;

import org.apache.activemq.ActiveMQConnectionFactory;

import javax.jms.*;
import java.io.IOException;

/**
 * activemq消费者-队列
 */
public class Consumer {

    private static final String DEFAULT_URL = "tcp://192.168.254.30:61616";
    private static final String QUEUE_NAME = "mercury-test";

    public static void main(String[] args) throws JMSException, IOException {

        System.out.println("------2号消费者---------");

        //1. activemqConnectionFactory
        ActiveMQConnectionFactory factory = new ActiveMQConnectionFactory(DEFAULT_URL);

        //2. activemqConnection
        Connection connection = factory.createConnection();

        //3.开启连接 connection
        connection.start();

        //4.session
        Session session = connection.createSession(false, Session.AUTO_ACKNOWLEDGE);

        //5.设置队列
        Queue queue = session.createQueue(QUEUE_NAME);

        //6.创建consumer
        MessageConsumer consumer = session.createConsumer(queue);

        //7. 接收消息
        //方式1：  recieve（）
        /*while(true){
            Message msg = consumer.receive();
            if(msg !=null && msg instanceof TextMessage){
                TextMessage textMessage = (TextMessage)msg;
                System.out.println(textMessage.getText());
            }else{
                break;
            }
        }*/

        //方式2： recieve(timeout)
        /*while(true){
            Message msg = consumer.receive(40);
            if(msg != null && msg instanceof TextMessage){
                TextMessage textMessage = (TextMessage)msg;
                System.out.println(textMessage.getText());
            }else{
                break;
            }
        }*/

        //方式3
        consumer.setMessageListener(msg->{
            if(msg != null && msg instanceof TextMessage){
                TextMessage textMessage = (TextMessage)msg;
                try {
                    System.out.println(textMessage.getText());
                } catch (JMSException e) {
                    e.printStackTrace();
                }
            }
        });
        //挂起控制台，不然还没有监听到，就已经关闭资源了
        System.in.read();

        //8. 关闭资源
        consumer.close();
        session.close();
        connection.close();
    }
}